import RecommendAPI from '../../../common/api/recommend/recommend.api.js';
import doT from '../../../../vendor/template/doT.js';

(function (window, document, $) {
    const salesplanmainTemplate = doT.template($('#salesplanmain-template').text());
    let _vm, _res, operatarr = [], index, resTotal = [], listindex = "";
    let _page = {
        pageSize: 10,
        pageIndex: 0,
        totalPages: -1,
    }
    $(function () {
        _vm = new Vue({
            el: "#recommendmain",
            data() {
                return {
                    page: { ..._page },
                    entries: [],
                    userInfo: "",
                }
            }
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _initCommand()
        pullLoad()
        _initSlide()
        $('#recommend-poster').trigger('click')
        _initMain()
    });

    //TODO : 命名初始化
    const _initCommand = () => {
        $('#my-recommend').on('click', function () {
            _initPage()
            _vm.entries = []
            _initDataTable()
            $('#postermain').css('display', 'none')
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
        })
        $('#recommend-poster').on('click', function () {
            $('#myrecommend').css('display', 'none')
            $('#recommend_container-Info').css('display', 'none')

            $('#postermain').css('display', 'block')
            // initPoster()           
            $(this).addClass('weui-bar__item--on').siblings().removeClass('weui-bar__item--on');
        })
    }
    // 初始化海报
    const initPoster = async () => {
        // 获取登录用户信息
        let userIfon = await RecommendAPI.getLoginUserToStaff()
        $.showLoading();
        _vm.userInfo = `内推码：${userIfon.numCode}（${userIfon.name}）`
        let encodeInfo = encodeURIComponent(`?jobcode=${userIfon.numCode}&name=${userIfon.name}&type=onlysub`)
        $(`#interCode`).empty().qrcode({
            correctLevel: 1,
            width: 150,
            height: 150,
            background: "#fff",
            fill: "#000",
            text: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1ad638ad9b08700d&redirect_uri=https://www.ynsnjt.cn/H5Info/html/features/biz/jobposts/jobmain.html${encodeInfo}&response_type=code&scope=snsapi_base&state=gh_23661350a4c9#wechat_redirect`
            // text: `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx32ae207716b83acc&redirect_uri=https://wg.ynsnjt.net/H5Info/html/features/biz/jobposts/jobmain.html${encodeInfo}&response_type=code&scope=snsapi_base&state=gh_ed3f734c86ea#wechat_redirect`
        });
        let canvas = $(`#interCode canvas`);
        let img = canvas[0].toDataURL("image/png");
        $(`#interCodeMain`).empty().append(`<div><img src="${img}" id="img-qcode"></div>`)
    }

    const _initMain = async () => {
        await initPoster()
        var targetDom = document.getElementById('csposter');
        var csposterimg = document.querySelector('.csposterimg')
        let a = targetDom.scrollWidth
        let b = targetDom.scrollHeight
        html2canvas(targetDom, {
            useCORS: true,// 开启跨域配置
            height: targetDom.scrollHeight,//canvas高
            width: targetDom.scrollWidth, //canvas宽
            scale: 250, //按比例增加分辨率 (2=双倍).
            dpi: window.devicePixelRatio * 250,//设备像素比
            // 可解决图片不透明问题以及有白边
            backgroundColor: 'white',
            x: targetDom.offsetLeft,
            y: targetDom.offsetTop,
        }).then(canvas => {
            canvas.style.width = "100%";
            canvas.style.height = "auto";
            let url = canvas.toDataURL("image/png", 0.8);
            var imgUri = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 获取生成的图片的url
            $(`#csposter`).css('display', 'none')
            $(`#hideimg`).css('display', 'block')
            $(`#hideimg`).empty().append(`<img style="width: ${a}px; height: ${b}px" src="${imgUri} ">`)
            $.hideLoading();

        });
    }


    // 请求列表数据
    const _initDataTable = async () => {
        // 获取登录用户信息
        let userIfon = await RecommendAPI.getLoginUserToStaff()
        let _data = _vm.page;
        $('.recomcode:last').css('margin-bottom', '10px')
        RecommendAPI.mycomList(Object.assign({
            code: userIfon.numCode
        }, _data)).then(res => {
            $('#myrecommend').css('display', 'block')
            $('#recommend_container-Info').css('display', 'block')
            _page = {
                pageSize: 10,
                pageIndex: _data.pageIndex + 1,
                totalPages: res.totalPages
            }
            let entriesInfo = []
            _vm._data.page = Object.assign({}, _page);
            entriesInfo.push(...res.items)
            _vm.entries = [..._vm.entries, ...entriesInfo];
        });
    }
    // 初始化页码
    const _initPage = () => {
        _page = {
            pageSize: 10,
            pageIndex: 0,
            totalPages: -1,
        }
        _vm._data.page = Object.assign({}, _page);
    }


    // 下拉加载
    // recommend_container-Info
    const _initSlide = () => {
        //分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
        let disY, startY, endY, timer, t, pullheight;

        // 触摸开始
        $('#recommend_container-Info').on('touchstart', function (e) {
            startY = e.originalEvent.changedTouches[0].pageY;//开始时的坐标
            console.log($('#recommend_container-Info').scrollTop())
        });
        // 移动中
        $('#recommend_container-Info').on('touchmove', function (e) {
            console.log($('#recommend_container-Info').scrollTop())
            if ($('#recommend_container-Info').scrollTop() <= 0) {
                endY = e.originalEvent.changedTouches[0].pageY;
                disY = endY - startY;//移动后的坐标减去开始坐标，滑动距离。
                if (isTop() && disY > 0) {
                    e.preventDefault();
                }
                if (disY < 60) {
                    $('#pull-down').css({
                        height: disY + 'px'//父盒子的高度随着滑动距离变化，有最大值。
                    });
                }
                else {
                    $('#pull-down').css({
                        height: 60 + 'px'//父盒子的最大高度
                    });
                }
                // 结束时
                $('#recommend_container-Info').on('touchend', function (e) {
                    clearInterval(timer);
                    endY = e.originalEvent.changedTouches[0].pageY;
                    disY = endY - startY;
                    if (isTop() && disY > 0) {
                        timer = setInterval(function () {
                            $('#pull-down').css({
                                height: 0 + 'px',//松手后的返回。
                            });
                            clearInterval(timer);
                            _initPage()
                            _vm.entries = []
                            _initDataTable();//加载数据 
                        }, 300)
                    } else {
                        $('#pull-down').css({
                            height: 0 + 'px',//松手后的返回。
                        });
                    }
                })
            }
            else {
                $('#recommend_container-Info').off('touchend')
            }


        });
    }
    const isTop = () => {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        return t === 0 ? true : false;
    }

    //TODO : 上拉加载
    const pullLoad = () => {
        // 监听滚动的父容器
        $("#recommend_container-Info").infinite().on("infinite", function () {
            let _data = _vm._data.page;
            if (_data.pageIndex == _data.totalPages) {
                return
            }
            let self = this;
            if (self.loading) return;
            self.loading = true;
            setTimeout(function () {
                _initDataTable();
                self.loading = false;
            }, 500);   //模拟延迟
        });
    }

})(window, document, jQuery)